import { reqregister } from "../../request/api"
import { Toast } from "antd-mobile"

//状态
const initState = {
    //初始化表单数据
    user: {
        phone: "",
        nickname: "",
        password: ""
    }
}

//actionType
const TYPES = {
    //修改user type
    REGISTER_CHANGE_USER: 'REGISTER_CHANGE_USER'
}

//修改state reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        case TYPES.REGISTER_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        default:
            return state;
    }
}

//做逻辑和异步的actions actionsCreators
export const actions = {
    changeUser: (key, value) => ({ type: TYPES.REGISTER_CHANGE_USER, key, value }),

    doregister: (push) => {
        return (dispatch, getState) => {
            let user = getUser(getState());

            reqregister(user).then(res => {
                if (res.data.code == 200) {
                    Toast.show({
                        content: res.data.msg
                    })
                    push("/login");
                } else {
                    Toast.show({
                        content: res.data.msg
                    })
                }
            })
        }
    }
}

//导出数据 Selectors
export const getUser = state => state.register.user;

//导出reducer
export default reducer;